﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;

public class ResourcesUpdate : MonoBehaviour {
    private string serverPath = "http://127.0.0.1:8080/Resources/IOS/version.txt";

    private string loadPath = "http://127.0.0.1:8080/Resources/IOS/";

    public Dictionary<string, string> ServerVersionDic = new Dictionary<string, string>();

    public Dictionary<string, string> localVersionDic = new Dictionary<string, string>();

    private List<string> updatList = new List<string>();

    public int Threadcount = 10;

    private int loadCount = 0;
    private void Awake()
    {
        //TODO: 封装路径
    }

    private void Start()
    {
        CheckVerison();
    }

    public void CheckVerison()
    {
        LoadAsset(serverPath, handleServerVersion);

    }
    //更新本地的version配置    
    private void UpdateLocalVersionFile()
    {
        StringBuilder versions = new StringBuilder();
        foreach (var item in ServerVersionDic)
        {
            versions.Append(item.Key).Append(",").Append(item.Value).Append("\n");
        }
        string path = Application.persistentDataPath + "/Resources";
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        FileStream stream = new FileStream(Application.persistentDataPath + "/Resources/" + "version.txt", FileMode.Create);
        byte[] data = Encoding.UTF8.GetBytes(versions.ToString());
        stream.Write(data, 0, data.Length);
        stream.Flush();

    }
    public void UpdateResource()
    {
        if (updatList.Count < 0) return;

        UpdateLocalVersionFile();
        for (int i = 0; i < updatList.Count; i++)
        {
            LoadAsset(loadPath+ updatList[i], OnLoadComplete);
        }

    }
    public Action<System.Object> OnLoadComplete = (Param) =>
    {

        WWW www = (WWW)Param;
        byte[] data = www.bytes;
        string path = www.url.Substring(www.url.IndexOf("Resources"));
        string filePath = Application.persistentDataPath + "/" + path;
        string[] direc = path.Split('/');
        StringBuilder sb = new StringBuilder();

        sb.Append(Application.persistentDataPath);

        for (int i = 0; i < direc.Length - 1; i++)
        {
            sb.Append("/" + direc[i]);
            if (!Directory.Exists(sb.ToString()))
            {
                Directory.CreateDirectory(sb.ToString());
            }
        }

        FileStream stream = new FileStream(filePath, FileMode.Create);
        stream.Write(data, 0, data.Length);
        stream.Flush();
        stream.Close();
        www = null;
        if(www.assetBundle!=null)
        {
            www.assetBundle.Unload(false);
        }
        Param = null;
    };

    // 本地Version
    public bool LocalVersionLoad()
    {
        string path = Application.persistentDataPath + "/Resources/version.txt";
        List<string> saveList = new List<string>();
        FileInfo info = new FileInfo(path);  //获取路径下文件信息  
        if (!info.Exists)   //如果不存在返回  
        {
            Debug.Log("!exist    " + path);
            return false;
        }
        else
        {
            StreamReader sr = null;
            sr = File.OpenText(path);  //存在则打开文件  

            string line;
            while ((line = sr.ReadLine()) != null)  // 一行一行读取文件  
            {
                saveList.Add(line);    //向保存文件集合添加 路径字符串  
            }

            sr.Close();
            sr.Dispose();
            Debug.Log(saveList.Count);
            if (saveList.Count > 0)
            {
                for (int i = 0; i < saveList.Count; i++)
                {
                    if (saveList[i] != "")
                    {
                        string key = saveList[i].Split(',')[0];
                        string val = saveList[i].Split(',')[1];
                        localVersionDic.Add(key, val);
                        Debug.Log(val);
                        key = null;
                        val = null;
                    }
                }
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    private void handleServerVersion(System.Object Param)
    {
        WWW www = (WWW)Param;
        Debug.Log(www.text);
        string[] ver = www.text.Split('\n');
        www = null;
        if (ver.Length > 0)
        {
            for (int i = 0; i < ver.Length; i++)
            {
                if (ver[i] != "")
                {
                    string key = ver[i].Split(',')[0];
                    string val = ver[i].Split(',')[1];
                    ServerVersionDic.Add(key, val);
                    Debug.Log(val);
                    key = null;
                    val = null;
                }

            }
        }
        if (LocalVersionLoad())
        {
            var enumer = ServerVersionDic.GetEnumerator();
            while(enumer.MoveNext())
            {
                var current = enumer.Current;
                if (localVersionDic.ContainsKey(current.Key))
                {
                    if (localVersionDic[current.Key] == current.Value)
                    {
                        continue;
                    }
                    else
                    {
                        updatList.Add(current.Key);
                    }
                }
                else
                {
                    updatList.Add(current.Key);
                }
            }

        }
        else
        {
            var enumer = ServerVersionDic.GetEnumerator();
            while (enumer.MoveNext())
            {
                var current = enumer.Current;
                updatList.Add(current.Key);
            }
        }
        UpdateResource();
    }
    public void LoadAsset(string path, Action<System.Object> act = null)
    {
        StartCoroutine(Load(path, act));
    }
    IEnumerator Load(string path, Action<System.Object> Succeed = null)
    {

        WWW www = new WWW(path);
        yield return www;
        if (www.error == null)
        {
            if (Succeed != null)
                Succeed(www);
        }
        else
        {
            Debug.Log(www.error);
        }

        www.Dispose();
    }
}
